//
//  HomeViewcontroller.m
//  Fantasia
//
//  Created by kongkong on 16/9/17.
//  Copyright © 2016年 Kongkong. All rights reserved.
//

#import "HomeViewcontroller.h"
#import "DeviceHomeViewController.h"
#import "DeviceModel.h"
#import "SettingViewController.h"

@interface HomeViewcontroller () <UITableViewDelegate, UITableViewDataSource>
@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) NSArray *deviceData;
@property(nonatomic, strong) NSArray *jxsData;

@property(nonatomic, assign) NSArray *data;

@property(nonatomic, strong) AKASegmentedControl *segment;
@end

@implementation HomeViewcontroller

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
//    self.view.backgroundColor = [UIColor colorWithRed:235 / 255.0 green:240 / 255.0 blue:243 / 255.0 alpha:1];

    
}

- (void)viewWillAppear:(BOOL)animated {
    static BOOL first = YES;
    if (!first) {
        [self loadData];
        [self loadContent];
        self.rootNavigationController.navigationBarHidden = NO;
    }
    first = NO;
//
//    if (self == self.rootNavigationController.viewControllers.firstObject) {
//        self.rootNavigationController.navigationBarHidden = YES;
//    } else {
//        self.rootNavigationController.navigationBarHidden = NO;
//    }
}

- (void)loadData {

//    KKRequest *request = [KKRequest requestWithApi:@"device" action:@"FETCH"];

    __weak typeof(self) weakSelf = self;

    [[KKRequestEngine api:@"device" action:@"FETCH"]
            async:^(id <KKResponseProtocol> response, id result) {
                __strong typeof(weakSelf) strongSelf = weakSelf;

                if (response.isSuccess) {
                    if ([[response originResult] isKindOfClass:[NSArray class]]) {
                        NSMutableArray *parserData = [NSMutableArray array];
                        [[response originResult] enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
                            DeviceModel *model = [DeviceModel modelWithData:obj];
                            [parserData addObject:model];
                        }];

                        strongSelf.deviceData = parserData;
                        strongSelf.data = strongSelf.deviceData;
                    }
                } else {
                    [response showError];
                }

                [strongSelf.tableView reloadData];
            }];
}

- (void)loadContent {
    self.navigationItem.titleView = self.segment;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"设置" style:UIBarButtonItemStylePlain target:self action:@selector(setting)];

    self.data = self.deviceData;

    [self.view addSubview:self.tableView];
}

- (void)setting{
    [[UIViewController rootNavigationController] pushViewController:[[SettingViewController alloc] init] animated:YES];
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
    }
    return _tableView;
}

- (AKASegmentedControl *)segment {
    if (!_segment) {
        _segment = [AKASegmentedControl segmentWithFrame:CGRectMake(100, self.vcTop + 20, self.view.width - 200, 40)
                                                  images:@[@"social-icon", @"star-icon"]
                                                  titles:@[@"所有设备", @"服务人员"]];

        __weak typeof(self) weakSelf = self;
        _segment.selectedAction = ^(NSInteger index) {

            typeof(weakSelf) strongSelf = weakSelf;
            if (0 == index) {
                strongSelf.data = strongSelf.deviceData;
            } else {
                strongSelf.data = strongSelf.jxsData;
            }
            [strongSelf.tableView reloadData];
        };

    }
    return _segment;
}

#pragma -mark UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
        cell.backgroundColor = [UIColor clearColor];
    }
    cell.textLabel.text = [(DeviceModel *) (self.data[indexPath.row]) name4Show];
    if (!cell.accessoryView) {
        UIView* view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 10)];
        view.layer.masksToBounds = YES;
        view.layer.cornerRadius = 2;
        cell.accessoryView = view;
    }
    
    cell.accessoryView.backgroundColor = ((DeviceModel*)(self.data[indexPath.row])).active?[UIColor greenColor]:[UIColor redColor];
    
//    cell.detailTextLabel.text = ((DeviceModel *) self.data[indexPath.row]).deviceId;
//    cell.textLabel.text = self.data[indexPath.row];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (self.data == self.jxsData) {
        NSLog(@"%@", self.rootNavigationController.viewControllers);
        HomeViewcontroller *vc = [[HomeViewcontroller alloc] init];
        vc.title = self.data[indexPath.row];
        [self.rootNavigationController pushViewController:vc animated:YES];
    } else {
        DeviceModel *device = self.deviceData[indexPath.row];
        // 激活操作
        __weak typeof(self) weakSelf = self;
        [[[KKRequestEngine api:@"device" action:@"ACTIVE"]
                parameter:@{@"deviceID": device.deviceId}]
                async:^(id <KKResponseProtocol> response, id result) {
                    if ([response isSuccess]) {
                        NSString *title = device.name4Show;
                        [[FantasiaStorage instance] setMemoryValue:title forKey:@"currentDevice"];
                        __strong typeof(weakSelf) strongSelf = weakSelf;
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [MBProgressHUD showHUDAddedTo:strongSelf.view animated:YES];
                        });
                        
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [strongSelf queryActive:device.deviceId count:0];
                        });
                    }
                }];

    }
}

- (void)queryActive:(NSString *)deviceId count:(NSInteger)count{

    if (count > 15) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        });
        return;
    }
    __weak typeof(self) weakSelf = self;
    [[[KKRequestEngine api:@"device" action:@"QUERYACTIVE"]
      parameter:@{@"deviceID":deviceId}]
     async:^(id <KKResponseProtocol> response, id result) {
         __strong typeof(weakSelf) strongSelf = weakSelf;
         if ([response isSuccess]) {
             dispatch_async(dispatch_get_main_queue(), ^{
                 [MBProgressHUD hideHUDForView:strongSelf.view animated:YES];
             });
             [[FantasiaStorage instance] setMemoryValue:deviceId forKey:@"currentDeviceID"];
             DeviceHomeViewController *vc = [[DeviceHomeViewController alloc] init];
             [strongSelf.rootNavigationController pushViewController:vc animated:YES];
         }
         else{
             dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                 [strongSelf queryActive:deviceId count:count+1];
             });
         }
         
    }];
}

#pragma -mark VC TOP

- (CGFloat)vcTop {
    if (self == self.rootNavigationController.viewControllers.firstObject) {
        return [UIApplication sharedApplication].statusBarFrame.size.height;
    }
    return self.rootNavigationController.navigationBar.bottom;
}

- (CGFloat)vcHeight {
    return self.view.height - self.vcTop;
}
@end
